﻿// Screenshot.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>

#define _AFXDLL
#include <afxwin.h>
#include <opencv\cv.h>
#include <opencv\highgui.h>

LPVOID screenCaptureData = NULL;
HBITMAP hBitmap;
HDC hDDC;
HDC hCDC;
int nWidth;
int nHeight;

void initGDI()
{
    nWidth = GetSystemMetrics(SM_CXSCREEN);
    nHeight = GetSystemMetrics(SM_CYSCREEN);
    screenCaptureData = new char[nWidth * nHeight * 4];
    memset(screenCaptureData, 0, nWidth);

    hDDC = GetDC(GetDesktopWindow());
    hCDC = CreateCompatibleDC(hDDC);
    hBitmap = CreateCompatibleBitmap(hDDC, nWidth, nHeight);
    SelectObject(hCDC, hBitmap);
}

void gdiScreenCapture(LPVOID screenCaptureData) {
    BitBlt(hCDC, 0, 0, nWidth, nHeight, hDDC, 0, 0, SRCCOPY);
    GetBitmapBits(hBitmap, nWidth * nHeight * 4, screenCaptureData);
    
    IplImage* img = cvCreateImage(cvSize(nWidth, nHeight), 8, 4);
    memcpy(img->imageData, screenCaptureData, nWidth * nHeight * 4);
    IplImage* img2 = cvCreateImage(cvSize(nWidth, nHeight), 8, 3);
    cvCvtColor(img, img2, CV_BGRA2BGR);
    cvSaveImage("rgba.jpg", img);
    cvWaitKey();

    cv::Mat src = cv::Mat(nHeight, nWidth, CV_8UC4);
    memcpy(src.data, screenCaptureData, nWidth * nHeight * 4);
    cv::Mat src2 = cv::Mat(nHeight, nWidth, CV_8UC3);
    cv::cvtColor(src, src2, CV_BGRA2BGR);
    imwrite("bbb.jpg", src2);



}

int main()
{
    std::cout << "Hello World!\n";
    initGDI();
    gdiScreenCapture(screenCaptureData);
    return 0;
}

